package com.dkd.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.dkd.common.core.domain.model.LoginUser;
import com.dkd.common.utils.SecurityUtils;
import com.dkd.common.utils.StringUtils;
import com.dkd.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        // 获取当前请求的登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(request);

        // 检查登录用户信息是否存在，并且当前上下文中没有身份验证信息
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            // 验证用户令牌的有效性
            tokenService.verifyToken(loginUser);

            // 创建身份验证令牌，用于表示用户已成功身份验证
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

            // 设置身份验证令牌的详细信息，包含请求相关的元数据
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            // 将身份验证信息存储在安全上下文中，以便在后续处理中使用
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        // 继续执行请求的过滤链
        chain.doFilter(request, response);
    }
}
